package com.ware4u.fx.news.server.config;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 主要数据库连接
 * @author CHN
 *
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "coreEntityManagerFactory",
						transactionManagerRef = "coreTransactionManager",
						basePackages = { "com.ware4u.*" })
public class DbConfig {
	
	@Primary
	@Bean(name = "coreDataSource")
	@ConfigurationProperties("spring.datasource")
	public DataSource dataSource() {
		DataSource ds = DataSourceBuilder.create().build();
		return ds;
	}
	

	@Primary
	@Bean(name = "coreEntityManagerFactory")
	public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
			@Qualifier("coreDataSource") DataSource dataSource) {
		return builder.dataSource(dataSource)
				.packages("com.ware4u.*")
				.persistenceUnit("core")
				.build();
	}

	@Primary
	@Bean(name = "coreTransactionManager")
	public PlatformTransactionManager transactionManager(
			@Qualifier("coreEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
		return new JpaTransactionManager(entityManagerFactory);
	}
}
